package idiolect.core;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class IOUtil {
    public static final File FOLDER = new File(new File(System.getProperty("user.home")), "idiolect");

    static {
        FOLDER.mkdirs();
    }

    public static void close(Closeable closeable) {
        if (closeable != null)
            try {
                closeable.close();
            } catch (IOException e) {
                //ignore
            }
    }

    public static byte[] getContent(URL pageURL) throws IOException {
        InputStream is = null;
        try {
            for (int i = 1; i <= 10; i++) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                try {
                    baos.reset();
                    byte[] buffer = new byte[32768];
                    HttpURLConnection connection = (HttpURLConnection) pageURL.openConnection();
                    if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
                        throw new IOException("Bad response code: " + connection.getResponseCode());
                    is = connection.getInputStream();
                    for (int l = is.read(buffer); l > 0; l = is.read(buffer))
                        baos.write(buffer, 0, l);
                } catch (IOException ioe) {
                    if (i < 10) {
                        try {
                            Thread.sleep(10000L);
                            continue;
                        } catch (InterruptedException e) {
                            throw new IOException("Interrupted");
                        }
                    } else {
                        throw ioe;
                    }
                }
                return baos.toByteArray();
            }
        } finally {
            close(is);
        }
        throw new IOException("Attempts limit exceeded");
    }
}
